<template>
  <div>
    <div class="container">
      <h5 class="page-header">患者信息查询</h5>

      <div class="query-box">
        <div class="basic-query">
          <div class="query-section-title">基础信息查询</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="姓名">
                <el-input v-model="queryParams.name" placeholder="请输入患者姓名" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="年龄范围">
                <el-input-number
                  v-model="queryParams.minAge"
                  :min="0"
                  :max="120"
                  placeholder="最小"
                  controls-position="right"
                  class="age-input"
                />
                <span class="range-separator">-</span>
                <el-input-number
                  v-model="queryParams.maxAge"
                  :min="0"
                  :max="120"
                  placeholder="最大"
                  controls-position="right"
                  class="age-input"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="性别">
                <el-select v-model="queryParams.gender" placeholder="请选择" clearable>
                  <el-option label="男" value="男" />
                  <el-option label="女" value="女" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="患者编号">
                <el-input v-model="queryParams.patientId" placeholder="请输入编号" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="advanced-query">
          <div class="advanced-query-header" @click="toggleAdvancedQuery">
            <div class="advanced-query-title">高级查询</div>
            <div class="toggle-icon">
              <el-icon :class="{ 'rotate-180': showAdvancedQuery }">
                <arrow-down />
              </el-icon>
            </div>
          </div>

          <el-collapse-transition>
            <div v-show="showAdvancedQuery" class="advanced-query-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="检查信息">
                    <div class="form-subgroup">
                      <div class="form-label">CA72-4指标 (U/mL)</div>
                      <div class="range-inputs">
                        <el-input-number
                          v-model="queryParams.ca72Min"
                          :min="0"
                          placeholder="最小值"
                          controls-position="right"
                          class="range-input"
                        />
                        <span class="range-separator">-</span>
                        <el-input-number
                          v-model="queryParams.ca72Max"
                          :min="0"
                          placeholder="最大值"
                          controls-position="right"
                          class="range-input"
                        />
                      </div>
                    </div>
                    <div class="form-subgroup" style="margin-top: 15px;">
                      <div class="form-label">B超检查结果</div>
                      <el-input v-model="queryParams.ultrasound" placeholder="请输入关键词" clearable />
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="检验信息">
                    <div class="form-subgroup">
                      <div class="form-label">血尿酸浓度 (μmol/L)</div>
                      <div class="range-inputs">
                        <el-input-number
                          v-model="queryParams.uricAcidMin"
                          :min="0"
                          placeholder="最小值"
                          controls-position="right"
                          class="range-input"
                        />
                        <span class="range-separator">-</span>
                        <el-input-number
                          v-model="queryParams.uricAcidMax"
                          :min="0"
                          placeholder="最大值"
                          controls-position="right"
                          class="range-input"
                        />
                      </div>
                    </div>
                    <div class="form-subgroup" style="margin-top: 15px;">
                      <div class="form-label">肌酐范围</div>
                      <div class="range-inputs">
                        <el-input-number
                          v-model="queryParams.creatinineMin"
                          :min="0"
                          placeholder="最小值"
                          controls-position="right"
                          class="range-input"
                        />
                        <span class="range-separator">-</span>
                        <el-input-number
                          v-model="queryParams.creatinineMax"
                          :min="0"
                          placeholder="最大值"
                          controls-position="right"
                          class="range-input"
                        />
                      </div>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="诊疗信息">
                    <div class="form-subgroup">
                      <div class="form-label">就诊时间</div>
                      <el-date-picker
                        v-model="queryParams.clinicalDate"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                      />
                    </div>
                    <div class="form-subgroup" style="margin-top: 15px;">
                      <div class="form-label">诊断类型</div>
                      <el-select v-model="queryParams.first_flag" placeholder="请选择" clearable>
                        <el-option label="初诊" value="是" />
                        <el-option label="复诊" value="否" />
                      </el-select>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>
        </div>

        <div class="query-actions">
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQurey">查询</el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="basic_info.patient_id" label="患者编号" width="120" />
        <el-table-column prop="basic_info.name" label="姓名" width="100" />
        <el-table-column prop="basic_info.idcard" label="身份证号" width="180" />
        <el-table-column prop="basic_info.telephone" label="手机号" width="120" />
        <el-table-column prop="basic_info.first_flag" label="是否初诊" width="120"/>
        <el-table-column prop="basic_info.clinical_date" label="就诊时间" width="200" sortable>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <!--            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>


<script setup lang="ts">

import { ref,computed } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import {useRouter, useRoute} from 'vue-router'
const router = useRouter()  // 用于编程式导航
const route = useRoute()    // 用于获取当前路由信息
import {getAllPatients} from "@/demo-data/data/search"
// 在script setup顶部添加
import type { Patient } from '@/demo-data/types/patient'

// 在script setup顶部添加类型定义
interface TablePatient {
  trackCode: string;
  name: string;
  idCard: string;
  phone: string;
  isInitial: boolean;
  visitDate: string;
}

// 添加计算属性
// const paginatedData = computed(() => {
//   const start = (currentPage.value - 1) * pageSize.value
//   const end = start + pageSize.value
//   return tableData.value.slice(start, end)
// })


const showAdvancedQuery = ref(false)

const queryParams = ref({
  name: null, //患者姓名
  minAge: null, //最小年龄
  maxAge: null, //最大年龄
  gender: null, //性别
  patientId: null, //患者编号
  ca72Min: null, //最小CA72_4
  ca72Max: null, //最大的CA72_4
  clinicalDate:null,//就诊日期
  first_flag:null,//诊断类型
  ultrasound:null,// 超敏C反应蛋白关键词
  creatinineMin:null,//胱抑素B最小值
  creatinineMax:null,//胱抑素B最大值
  uricAcidMin:null, //血尿酸浓度最小值
  uricAcidMax:null, //血尿酸浓度最大值
})

const toggleAdvancedQuery = () => {
  showAdvancedQuery.value = !showAdvancedQuery.value
}

const tableData = ref([])
// //获取列表中的所有病人信息
tableData.value = getAllPatients()

const resetQuery = () => {
  queryParams.value = {
    name: null, //患者姓名
    minAge: null, //最小年龄
    maxAge: null, //最大年龄
    gender: null, //性别
    patientId: null, //患者编号
    ca72Min: null, //最小CA72_4
    ca72Max: null, //最大的CA72_4
    clinicalDate:null,//就诊日期
    first_flag:null,//诊断类型
    ultrasound:null,// 超敏C反应蛋白关键词
    creatinineMin:null,//胱抑素B最小值
    creatinineMax:null,//胱抑素B最大值
    uricAcidMin:null, //血尿酸浓度最小值
    uricAcidMax:null, //血尿酸浓度最大值
  }
  tableData.value = getAllPatients()
}

// 过滤函数
function filterPatients(patients:any, queryParams:any) {
  return patients.filter(patient => {
    console.log("patient",patient)
    const { basic_info, examination, lab_results } = patient;

    // 姓名过滤 (模糊匹配)
    if (queryParams.name &&
      !basic_info.name.includes(queryParams.name)) {
      return false;
    }

    // 年龄范围过滤
    if (queryParams.minAge && basic_info.age < queryParams.minAge) {
      console.log("patient.basic_info.age",patient.basic_info.age)
      return false;
    }
    if (queryParams.maxAge && basic_info.age > queryParams.maxAge) {
      return false;
    }

    // 性别过滤
    if (queryParams.gender && basic_info.gender !== queryParams.gender) {
      console.log("patient.basic_info.gender",patient.basic_info.gender)
      return false;
    }

    // 患者编号过滤
    if (queryParams.patientId &&
      !basic_info.patient_id.includes(queryParams.patientId)) {
      return false;
    }

    // CA72_4 范围过滤
    const ca72Value = parseFloat(examination.CA72_4.uml_value);
    if (queryParams.ca72Min && ca72Value < queryParams.ca72Min) {
      return false;
    }
    if (queryParams.ca72Max && ca72Value > queryParams.ca72Max) {
      return false;
    }

    // 就诊日期过滤
    if (queryParams.clinicalDate &&
      basic_info.clinical_date !== queryParams.clinicalDate) {
      return false;
    }

    // 初诊/复诊过滤
    if (queryParams.first_flag &&
      basic_info.first_flag !== queryParams.first_flag) {
      return false;
    }

    // 超声检查结果过滤
    if (queryParams.ultrasound) {
      const hasMatchingUltrasound = examination.ultrasound.some(
        item => item.result.includes(queryParams.ultrasound)
      );
      if (!hasMatchingUltrasound) {
        return false;
      }
    }

    // 肌酐范围过滤
    const creatinineValue = lab_results.creatinine.value;
    if (queryParams.creatinineMin &&
      creatinineValue < parseFloat(queryParams.creatinineMin)) {
      return false;
    }
    if (queryParams.creatinineMax &&
      creatinineValue > parseFloat(queryParams.creatinineMax)) {
      return false;
    }

    // 尿酸范围过滤
    const uricAcidValue = lab_results.urid_acid.ua.value;
    if (queryParams.uricAcidMin &&
      uricAcidValue < parseFloat(queryParams.uricAcidMin)) {
      return false;
    }
    if (queryParams.uricAcidMax  &&
      uricAcidValue > parseFloat(queryParams.uricAcidMax)) {
      return false;
    }

    // 所有条件都满足
    return true;
  });
}

// 手动查询函数
function handleQurey() {
  tableData.value = filterPatients(getAllPatients(), queryParams.value);
  console.log('过滤结果:', tableData.value);
}
// 表格数据
// const tableData = ref<TablePatient[]>(getAllPatients().map(patient => ({
//   trackCode: patient.basic_info.patient_id,
//   name: patient.basic_info.name,
//   idCard: patient.basic_info.idcard,
//   phone: patient.basic_info.telephone,
//   isInitial: patient.basic_info.first_flag === "是",
//   visitDate: patient.basic_info.clinical_date
// })))


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
// const total = ref(100)
// 修正总条目数
const total = ref(getAllPatients().length)  // 使用实际数据长度
// 排序处理
const handleSortChange = ({ column, prop, order }) => {
  console.log('排序:', prop, order)
  // 这里添加实际的排序逻辑
}

// 分页处理
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`)
  pageSize.value = val
  // 这里添加获取新数据的逻辑
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  currentPage.value = val
  // 这里添加获取新数据的逻辑
}

// 操作按钮处理
const handleView = (row:TablePatient) => {
  console.log('查看:', row)
  router.push({
    path:"patient",
    query:{
      // TODO:后期替换为json里面的id
      patientId: row.basic_info.patient_id
    }
  })
  // 这里添加查看逻辑
}

const handleDelete = (row) => {
  console.log('删除:', row)
  // 这里添加删除逻辑，可以使用 ElMessageBox 确认
  ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}



</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
  font-family: "Microsoft YaHei", sans-serif;
}

body {
  margin: 0;
  padding: 0;
  background-color: #f5f7fa;
  color: #333;
  font-size: 14px;
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px;
}

.page-header {
  background-color: #f8f9fa;
  padding: 10px 15px;
  border: 1px solid #e3e8ee;
  border-radius: 4px 4px 0 0;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 0;
}

.query-box {
  background-color: #fff;
  border: 1px solid #e3e8ee;
  border-top: none;
  border-radius: 0 0 4px 4px;
  padding: 15px;
  margin-bottom: 20px;
}

.basic-query {
  padding-bottom: 15px;
}

.query-section-title {
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-group {
  flex: 0 0 25%;
  max-width: 25%;
  padding: 0 10px;
  margin-bottom: 10px;
}

.form-label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
}

.form-control {
  display: block;
  width: 100%;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #495057;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #ced4da;
  border-radius: 4px;
  transition: border-color 0.15s ease-in-out;
}

.form-control:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.range-inputs {
  display: flex;
  align-items: center;
}

.range-inputs input {
  width: calc(50% - 10px);
}

.range-separator {
  width: 20px;
  text-align: center;
}

.advanced-query {
  padding-top: 15px;
  padding-bottom: 15px;
}

.advanced-query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.advanced-query-title {
  font-weight: bold;
}

.toggle-icon {
  color: #007bff;
  cursor: pointer;
}

.advanced-query-content {
  display: block;
}

.query-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  user-select: none;
  border: 1px solid transparent;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.5;
  border-radius: 4px;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out;
  margin-left: 10px;
  cursor: pointer;
}

.btn-default {
  color: #212529;
  background-color: #f8f9fa;
  border-color: #ced4da;
}

.btn-primary {
  color: #fff;
  background-color: #007bff;
  border-color: #007bff;
}

.table-container {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table {
  width: 100%;
  max-width: 100%;
  margin-bottom: 0;
  border-collapse: collapse;
}

.table th,
.table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e3e8ee;
}

.table th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.table tbody tr:hover {
  background-color: #f5f7fa;
}

.sort-icon {
  margin-left: 5px;
  color: #aaa;
}

.sort-active {
  color: #007bff;
}

.action-btns .btn {
  padding: 2px 8px;
  font-size: 12px;
}

.action-btns .btn-view {
  color: #007bff;
  background-color: transparent;
  border-color: #007bff;
}

.action-btns .btn-delete {
  color: #dc3545;
  background-color: transparent;
  border-color: #dc3545;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  align-items: center;
}

.pagination {
  display: flex;
  padding: 0;
  margin: 0;
  list-style: none;
}

.page-item {
  margin: 0 2px;
}

.page-link {
  position: relative;
  display: block;
  padding: 6px 12px;
  margin-left: -1px;
  line-height: 1.25;
  color: #007bff;
  background-color: #fff;
  border: 1px solid #dee2e6;
  text-decoration: none;
  cursor: pointer;
}

.page-item.active .page-link {
  z-index: 1;
  color: #fff;
  background-color: #007bff;
  border-color: #007bff;
}

.page-item.disabled .page-link {
  color: #6c757d;
  pointer-events: none;
  cursor: not-allowed;
  background-color: #fff;
  border-color: #dee2e6;
}

.page-item:first-child .page-link {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

.page-item:last-child .page-link {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.diagnosis-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.diagnosis-initial {
  background-color: #007bff;
}

.diagnosis-followup {
  background-color: #ffc107;
}
</style>

